<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-form :model="queryParams" ref="queryForm" :inline="true"  v-show="showSearch" label-width="80px">
          <el-form-item label="发送渠道" prop="channelName">
            <el-input v-model="queryParams.channelName" placeholder="请输入发送渠道" size="small" clearable style="width: 150px"/>
          </el-form-item>
      <!--    <el-form-item label="渠道编码" prop="channelCode">
            <el-input v-model="queryParams.channelCode" placeholder="请输入渠道编码" size="small" clearable style="width: 150px"/>
          </el-form-item>-->
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="任务状态" prop="taskStatusCode">
            <el-select @change="handleQuery" v-model="queryParams.taskStatusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option
                v-for="item in taskStatusCodeList"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务类型" prop="taskTypeCode">
            <el-select @change="handleQuery" v-model="queryParams.taskTypeCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option
                v-for="item in taskTypeCodeList"
                :key="item.dictCode"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveSmsSendTask']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateSmsSendTask']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteSmsSendTask']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="querySmsSendTaskPageResList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center" :selectable="checkSelectable"/>
          <el-table-column label="任务名称" align="left" prop="taskName"/>
          <el-table-column label="短信内容" align="left" prop="templateContent" :show-overflow-tooltip="true"/>
          <el-table-column label="发送渠道" align="left" prop="channelName"/>
          <el-table-column label="任务类型" align="left" prop="taskTypeName"  width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.taskTypeColor">{{scope.row.taskTypeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="定时时间" align="center" prop="timingTime"  width="200" >
            <template slot-scope="scope">
              <span v-if="scope.row.taskTypeCode==='SMS_TIMING_SEND'">{{scope.row.timingTime}}</span>
              <span v-if="scope.row.taskTypeCode!=='SMS_TIMING_SEND'">--</span>
            </template>
          </el-table-column>
          <el-table-column label="任务状态" align="left" prop="taskStatusName"  width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.taskStatusColor">{{scope.row.taskStatusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="备注说明" align="left" prop="remark"/>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-if="scope.row.taskStatusCode==='SMS_WAITING_EXECUTE'" v-hasPermi="['updateSmsSendTask']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-if="scope.row.taskStatusCode==='SMS_WAITING_EXECUTE'" v-hasPermi="['deleteSmsSendTask']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" v-if="scope.row.taskStatusCode==='SMS_WAITING_EXECUTE'" icon="el-icon-s-operation" @click="handleTaskDetailList(scope.row)">任务明细</el-button>
              <el-button size="mini" type="text" v-if="scope.row.taskStatusCode!=='SMS_WAITING_EXECUTE'" icon="el-icon-s-operation" @click="handleTaskDetailList(scope.row)">发送记录</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0"  :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="querySmsSendTaskPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.taskName" placeholder="请输入任务名称" maxlength="255" />
        </el-form-item>

        <el-form-item label="内容模板" prop="templateContent">
            <el-input readonly v-model="form.templateContent" placeholder="请点击右侧按钮选择内容模板">
            <template slot="append">
              <el-button type="primary" @click="smsTemplateOpen">
                选择内容模板
                <i class="el-icon-document-checked el-icon--right"></i>
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="任务类型" prop="taskTypeCode">
          <el-select @change="handleChangeTaskType" v-model="form.taskTypeCode" clearable style="width: 100%;" placeholder="请选择">
            <el-option
              v-for="item in taskTypeCodeList"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="定时时间" prop="timingTime" v-if="timingSendShow" :rules="{required: true, message:'定时时间必须选择。', trigger: 'blur'}">
          <el-date-picker
            v-model="form.timingTime"
            popper-class="no-atTheMoment"
            type="datetime"
            value-format="yyyy-MM-dd hh:mm"
            format="yyyy-MM-dd hh:mm"
            :picker-options="pickerOptions"
            placeholder="选择定时发送时间" style="width: 100%;" >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="手机号码" prop="taskContent" v-if="customModeShow" :rules="{required: true, message:'手机号码必须填写，多个请用英文逗号分隔。', trigger: 'blur'}">
          <el-input type="textarea" v-model="form.taskContent" :rows="5" placeholder="请输入手机号码，多个请用英文逗号分隔。示例：13888888888,13999999999" />
        </el-form-item>

        <el-form-item label="备注说明" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入备注说明" maxlength="255" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 短信内容模板选择组件 -->
    <SelectSmsTemplate ref="selectSmsTemplate" @handleSelectSmsTemplate="selectSmsTemplate" />

    <!-- 查看任务发送明细详情弹窗 -->
    <el-dialog :title="taskDetailTitle" :visible.sync="taskDetailOpen" width="800px" append-to-body>
        <!--beg-->
      <div>
        <el-table ref="taskDetailMultipleTable" :stripe="true" v-loading="taskDetailLoading" :data="taskDetailDataList">
          <el-table-column label="手机号码" align="left" prop="mobileNumber"  width="150" />
          <el-table-column label="发送状态" align="left" prop="sendStatusName"  width="100" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.sendStatusColor">{{scope.row.sendStatusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="发送时间" align="center" prop="sendTime" width="200" />
          <el-table-column label="结果说明" align="left" prop="remark"/>
        </el-table>
        <pagination v-show="taskDetailTotal>0"  :total="taskDetailTotal" :page.sync="queryTaskDetailParams.page" :limit.sync="queryTaskDetailParams.rows" @pagination="querySmsSendTaskDetailResList"/>
      </div>
      <!--end-->
    </el-dialog>
  </div>
</template>

<script>
  import { getDicListByDictCodeList } from '@/api/common/dict'
  import SelectSmsTemplate from '@/components/DuoJuHe/Common/SelectSmsTemplate'
  import {querySmsSendTaskPageResList, saveSmsSendTask, updateSmsSendTask, deleteSmsSendTaskBySendTaskId, querySmsSendTaskDetailResList, querySmsSendTaskResBySendTaskId} from '@/api/sms/smsSendTask'
  //默认查询参数
  let defaultQueryParams = {
    taskName: undefined,
    channelName: undefined,
    channelCode: undefined,
    startTime: undefined,
    endTime: undefined,
    taskStatusCode: undefined,
    taskTypeCode: undefined,
    taskModeCode: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: 'sendTaskAdmin',
    components: {
      SelectSmsTemplate
    },
    data() {
      return {
        formSearch: {},
        // 遮罩层
        loading: true,
        //定时类型
        timingSendShow: false,
        //自定义模式
        customModeShow: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        //操作短信发送任务
        dataList: [],
        // 日期范围
        dateRange: [],
        //任务状态
        taskStatusCodeList:[],
        //任务类型
        taskTypeCodeList:[],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        // 任务明细弹窗标题
        taskDetailTitle: "",
        // 是否显示任务明细弹出层
        taskDetailOpen: false,
        //任务明细弹窗遮罩层
        taskDetailLoading: false,
        //任务明细总条数
        taskDetailTotal: 0,
        //任务明细数据集合
        taskDetailDataList: [],
        // 查询参数
        queryTaskDetailParams: {
          taskId: "-1",
          page: 1,
          rows: 10
        },
        //列信息
        columns: [],
        //时间选择器限制
        pickerOptions: {
          // 选择当前月份或大于当前月份时间
          disabledDate(time) {
            return time.getTime() < Date.now()
          }
        },
        // 新增修改表单校验
        addUpdateOpenRules: {
          taskName: [
            { required: true, message: "任务名称不能为空",trigger: "blur" },
          ],
          taskTypeCode: [
            { required: true, message: "任务类型必须选择"},
          ],
          templateContent: [
            { required: true, message: "短信内容模板必须选择"},
          ]
        }
      }
    },
    created() {
      this.querySmsSendTaskPageResList()
      this.initDict()
    },
    methods: {
      //选择短信内容模板组件内容
      selectSmsTemplate(payload) {
        this.$set(this.form,"templateId", payload.templateId)
        this.$set(this.form,"templateContent", payload.content)
      },
      //打开短信发送内容模板选择组件
      smsTemplateOpen() {
        this.$refs.selectSmsTemplate.selectSmsTemplateOpen()
      },
      // 是否允许选择
      checkSelectable(row) {
        return row.taskStatusCode==='SMS_WAITING_EXECUTE'
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column) {
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.querySmsSendTaskPageResList()
      },

      //获取数据字典
      initDict(){
        let dictArr = ["SMS_TASK_TYPE","SMS_TASK_STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.taskStatusCodeList = JSON.parse(JSON.stringify(res.data['SMS_TASK_STATUS']));
          this.taskTypeCodeList = JSON.parse(JSON.stringify(res.data['SMS_TASK_TYPE']));
        });
      },

      /** 查询短信任务列表 */
      querySmsSendTaskPageResList() {
        this.loading = true
        querySmsSendTaskPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
            this.dataList = res.data.records
            this.total = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.loading = false
        })
      },

      //处理选择任务类型方法
      handleChangeTaskType(value){
        if ("SMS_TIMING_SEND"===value){
          //如果是定时发送，则显示定时选择器
          this.timingSendShow = true
        }else {
          this.timingSendShow = false
        }
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "添加任务";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        const taskId={taskId:row.taskId}
        querySmsSendTaskResBySendTaskId(taskId).then(response => {
          let data = response.data;
          //修改表单填充
          this.form = data;
          //是否显示定时时间选择器
          this.timingSendShow = "SMS_TIMING_SEND" === data.taskTypeCode;
        })
        this.addUpdateOpen = true;
        this.title = "修改任务";
      },

      /** 查询发送详情集合 */
      handleTaskDetailList(row){
        this.taskDetailOpen = true;
        this.taskDetailTitle = row.taskStatusCode!=='SMS_WAITING_EXECUTE'?"发送记录":"任务明细";
        this.queryTaskDetailParams.page = 1
        this.queryTaskDetailParams.taskId = row.taskId
        this.querySmsSendTaskDetailResList()
      },

      /** 分页查询明细 */
      querySmsSendTaskDetailResList(){
        this.taskDetailLoading = true
        querySmsSendTaskDetailResList(this.queryTaskDetailParams).then(res => {
            this.taskDetailDataList = res.data.records
            this.taskDetailTotal = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.taskDetailLoading = false
        })
      },

      /**获取当前时间*/
      getTimeStr(){
        const date = new Date()
        const year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hours = date.getHours();
        let minutes = date.getMinutes();
        if (month&&month<10) {
          month = "0" + month;
        }
        if (day&&day<10) {
          day = "0" + day;
        }
        if (hours&&hours<10) {
          hours = "0" + hours;
        }
        if (minutes&&minutes<10) {
          minutes = "0" + minutes;
        }
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选任务?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const taskId={taskId:row.taskId}
          return deleteSmsSendTaskBySendTaskId(taskId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.querySmsSendTaskPageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.taskTypeCode&&"SMS_IMMEDIATELY_SEND"===this.form.taskTypeCode){
              this.form.timingTime = this.getTimeStr();
            }
            let taskContent = this.form.taskContent;
            if (taskContent){
              this.form.taskContentList = taskContent.split(",");
            }
            if (this.form.taskId !== undefined) {
              updateSmsSendTask(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsSendTaskPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSmsSendTask(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySmsSendTaskPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },

      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.querySmsSendTaskPageResList()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.taskDetailOpen = false;
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          taskId: undefined,
          channelId: undefined,
          channelName: undefined,
          templateId: undefined,
          templateContent: undefined,
          taskName: undefined,
          taskTypeCode: "",
          timingTime: undefined,
          remark:undefined,
          taskContentList:[],
          taskContent:undefined,
          taskModeCode: "SMS_CUSTOM_MODE"
        };
        this.resetForm('form')
      }
    }
  }
</script>
